import React, { useEffect, useState } from 'react'
import style from './cardListEmployees.module.scss'
import CardEmployeeSmall from '../CardEmployeeSmall/CardEmployeeSmall'
import { useAppSelector } from '../../../starter/hooks/redux'
import { useDrop } from 'react-dnd'
import { IProjectToEmployeeLink } from '../../../starter/model/interfaces'
import { Button, ButtonProps } from 'antd'
import CreatePeriod from '../CreatePeriod/CreatePeriod'
import { useActions } from '../../../starter/hooks/actions'
import { store } from '../../../starter/redux/store'
import {
  useDeleteProjectEmployeeLinkMutation,
  useUpdateProjectEmployeeLinksMutation
} from '../../../starter/api/projectEmployeeLinksApi'
import { DeleteOutlined } from '@ant-design/icons'

const CardListEmployees = () => {
  const { employees } = useAppSelector(state => state.employees)
  const modalData = useAppSelector(state => state.modal)
  const {onShowModal, setModalData, setTmpPeriod} = useActions()
  const [updateLink, {isLoading: isLoadingUpdateLink, isSuccess: isSuccessUpdateLink, isError: isErrorUpdateLink}] = useUpdateProjectEmployeeLinksMutation()
  const [dropLink, {isLoading: isLoadingDropLink, isSuccess: isSuccessDropLink, isError: isErrorDropLink}] = useDeleteProjectEmployeeLinkMutation()

  useEffect(() => {

  }, [isErrorUpdateLink, isErrorDropLink])

  useEffect(() => {
    if (isSuccessUpdateLink || isSuccessDropLink) {
      onShowModal(false)
    }
  }, [isSuccessUpdateLink, isSuccessDropLink])

  useEffect(() => {
    const _buttonSet = modalData.buttonSet.map(button => ({
      ...button,
      loading: isLoadingUpdateLink || isLoadingDropLink
    }))

    setModalData({
      buttonSet: _buttonSet,
      footer: _buttonSet.map((item, index) => <Button key={index} {...item}/>)
    })
  }, [ isLoadingUpdateLink, isLoadingDropLink])


  const [{ isActive }, dropRef] = useDrop({
    accept: 'employee',
    drop(item: IProjectToEmployeeLink, monitor) {
      if (item.employee && item.project && item.periods && item.periods.length <= 1) {
        dropLink(item)
      } else {
        onShowModal(true)
        const buttonSet : ButtonProps[] = [
          {
            type: 'primary',
            onClick: () => removeLink(item),
            children: 'Ok'
          },
          {
            onClick: () => onShowModal(false),
            children: 'Cancel'
          }
        ]
        setModalData(
          {
            title: 'выберите удаляемые периоды',
            content: <CreatePeriod onChange={setTmpPeriod} periods={item ? item.periods : []} showRange={false}/>,
            footer: buttonSet.map((item, index) => <Button key={index} {...item}/>)
          }
        )
      }
    },
    collect: monitor => ({
      isActive: monitor.canDrop() && monitor.isOver(),
    })
  })

  const removeLink = (linkItem: IProjectToEmployeeLink) => {
    const {selectedPeriods: selectedTmpPeriods} = {...store.getState()?.tmp}
    const _linkItem: IProjectToEmployeeLink = {
      ...linkItem,
      periods: linkItem && selectedTmpPeriods ? linkItem.periods.filter(period => !selectedTmpPeriods.map(item => item.id).includes(period.id)) || [] : linkItem.periods
    }

    if (_linkItem.periods.length === 0) {
      dropLink(linkItem)
    } else {
      updateLink(_linkItem)
    }
  }

  return (
    <div className={style.wrapper}
         ref={dropRef}
    >
      { isActive &&
        <div className={style.remove}>
          <DeleteOutlined className={style.removeIcon} />
        </div>
      }
      {
        employees && employees.map(employee => (<CardEmployeeSmall key={employee._id} employee={employee}/>))
      }
    </div>
  )
}

export default CardListEmployees
